òɾۿûѧϰʹá
ԭַhttps://www.joinquant.com/post/11292

ԭһ˵ʽ鵽ԭĺ߽ۡ


ԭĲԴ£

import jqdata
# talibΪtl
import talib as tl
# numpyΪtl
import numpy as np
#  technical_analysis 
from jqlib.technical_analysis import *
'''
================================================================================
زǰ
================================================================================
'''

#### ò  мֻƱ
MAX_OWN_NUM = 2
#### ò  뵥ֻƱ,ʹÿʽļ֮1
CASH_SP_COUNT = 2
#### ò  ÿ쿪,ʹöٿʽ
CASH_MAX_USE  = 20000
#### ò  ÿֻƱʹöʽ
CASH_MAX_USE_PERSTOCK = 10000

#   ʼ趨׼ȵ
def initialize(context):
    # ̬Ȩģʽ(ʵ۸)
    set_option('use_real_price', True)
    # ݵ־ log.info()
    log.info('ʼʼȫֻһ')
    log.set_level('order', 'error')
    g.HighAfterEntry = {} # ֲֹƱ ߼
    g.holdday = {}# ֲֹƱ ֲ
    ### Ʊ趨 ###
    #׷:
    set_order_cost(OrderCost(close_tax=0.001#ӡ˰
                            , open_commission=0.0003#Ӷ
                            , close_commission=0.0003
                            , min_commission=5), type='stock')
    ## к
      # ǰ
    run_daily(before_market_open, time='before_open') 
      # 
    run_daily(market_open, time='close-10m')
      # ̺
    run_daily(after_market_close, time='after_close')
    

'''
================================================================================
ÿ쿪ǰ
================================================================================
'''
#   ǰ     
def before_market_open(context):
    g.date = context.current_dt.strftime("%Y-%m-%d")
    # ʱ
    log.info('ǰ:'+str(context.current_dt.time()))
    #趨ѡƱأ֤800
    g.codelist = get_index_stocks('000300.XSHG')
    #g.codelist = ['601231.XSHG']
    #log.info('codelist:',g.codelist)
    g.codelist = gl_tp(g.codelist)# ͣƹƱ
    #log.info('codelist_tp:',g.codelist)
    g.codelist = gl_st(g.codelist)# STƱ
    #log.info('codelist_st:',g.codelist)
    # ǰ g.HighAfterEntry ֲֹƱʷ߼
    update_HighAfterEntry(context)
   
    
## ͣƹƱ
def gl_tp(codelist):
    current_data = get_current_data()
    codelist = [code for code in codelist if not current_data[code].paused]
    return codelist
## STƱ
def gl_st(codelist):
    current_data = get_current_data()
    codelist = [code for code in codelist if not current_data[code].is_st]
    return codelist
##   g.HighAfterEntry ֲֹƱʷ߼
def update_HighAfterEntry(context):
    if len(g.HighAfterEntry) > 0:
        for code in g.HighAfterEntry.keys():
            sj = get_bars(code, 1, unit='1d',fields=['close'],include_now=True)
            if g.HighAfterEntry[code] < sj['close'][-1]:
                g.HighAfterEntry[code] = sj['close'][-1]
            else:
                pass
            #log.info('߼:', g.HighAfterEntry)

'''
================================================================================
================================================================================
'''
#   
def market_open(context):
    
    log.info(':'+str(context.current_dt.time()))
    sell_pd(context)##  ɨж
    tdsell(context)##  
    
    buy_pd(context)##  ɨж
    tdbuy(context)##  
'''
================================================================================
ÿ콻ʱ 
================================================================================
'''
def Check_Stocks(context):
    security = g.codelist
    Stocks = get_fundamentals(query(
            valuation.code,
            valuation.pb_ratio,
            balance.total_assets,
            balance.total_liability,
            balance.total_current_assets,
            balance.total_current_liability
        ).filter(
            valuation.code.in_(security),
            valuation.pb_ratio < 2,
            valuation.pb_ratio > 0,
            balance.total_current_assets/balance.total_current_liability > 1.2
        ))

    Stocks['Debt_Asset'] = Stocks['total_liability']/Stocks['total_assets']
    me = Stocks['Debt_Asset'].median()
    Code = Stocks[Stocks['Debt_Asset'] > me].code
    return list(Code)
##  ɨж
def buy_pd(context):
    buy = []
    own_num = len(context.portfolio.positions)#ǰֲ
    if own_num < MAX_OWN_NUM:#ǰֲ<ֲִѡ
        codelist = Check_Stocks(context)
        for code in codelist:
            if code in context.portfolio.positions:#޳ֲֹƱ
                continue#òִʣ룬ѭ
            if  btj1(code)==False or btj2(code)==False:
                continue
            #elif btj3(code)        == False:
            #    continue
            #elif btj4(context,code)== False:
            #    continue
       
            else :
                buy.append(code)#appendӣbuyӹƱ
            #ﵽǣֹͣѡ
            if len(buy) + own_num == MAX_OWN_NUM:
                break

    #set()һظԪؼ,Լ㽻'&''-''|'
    g.tdbuy = list(set(buy) - set(g.tdsell))#޳ĹƱ
    #log.info(' tdbuy ',g.tdbuy)#־
    return
##  
def tdbuy(context):
    buylist = g.tdbuy
    if len(buylist)>0:#len=ȣ б>0
        #ÿʽ=min(趨.ֽ,˻ֽ)/max(ֻ,뵥ֻƱ,ʹÿʽļ֮1
        per_cash = min(CASH_MAX_USE,context.portfolio.available_cash)/max(len(buylist),CASH_SP_COUNT)
    else:#
        per_cash = 0
    for code in buylist:
        #  cash Ʊ
        order_value(code, per_cash)
        # ¼
        #log.info("֣ %s" % (code))    
    return
####1
def btj1(code):
    a = bei_li(code)
    b = RS(code)
    tj = False
    if  a == -1:
        tj = True
    return tj
def btj2(code):
    a = bei_li(code)
    b = RS(code)
    tj = False
    if  b == -1:
        tj = True
    return tj
####2
'''
================================================================================
ÿ콻ʱ 
================================================================================
'''
##  ɨж
def sell_pd(context):
    g.tdsell = []
    if len(context.portfolio.positions)>0:
        for code in context.portfolio.positions:#Ʊڳֲ
            if  stj1(code) == True :
                g.tdsell.append(code)
    #log.info('tdsell ',g.tdsell)
##  
def tdsell(context):
    sell_list = g.tdsell
    
    for code in sell_list:
        # йƱ,ʹֻƱճΪ0
        order_target(code, 0)
        # ¼
        #log.info("ƽ֣ %s" % (code))
    return
####1
def stj1(code):
    a = bei_li(code)
    b = RS(code)
    tj = False
    if  b == 1 or a==1:
        tj = True
    return tj


'''
================================================================================
̺
================================================================================
'''
#   ̺к  
def after_market_close(context):
    log.info(str('̺:'+str(context.current_dt.time())))
    ji_lu(context)
    
    #
    record (a=GetCurrentPositionCount(context))
    #record ()
    #record ()
    log.info('һ\nTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT')

def ji_lu(context):
    trades = get_orders()    #õгɽ¼
    for t in trades.values():
        #if t.is_buy and t.filled>0:
        if t.action == 'open' and t.filled>0:
            x = str(t.security)
            g.HighAfterEntry[x] = t.price
        #elif not t.is_buy and t.filled>0:
        elif t.action == 'close' and t.filled>0:
            xx = str(t.security)
            try:
                del g.HighAfterEntry[xx]
            except:
                g.HighAfterEntry[xx] = 0
        log.info("ɽ¼ \n\
                              룺%s\n\
                              %s\n\
                              ۸%s\n\
                              %s\n"
                              ,t.security,t.action,t.price,t.filled)

##  ȡǰмֻƱ
def GetCurrentPositionCount(context):
    c=0#ʼΪ0ֻղ
              # context.portfolio.positions = ǰֲ
    for code in context.portfolio.positions:
        if context.portfolio.positions[code].total_amount>0:#λ>0
            c+=1   #c+1     
    return c

'''
================================================================================

================================================================================
'''


def bei_li(code):
    security=code
    check_date=g.date
    TRIX1,MATRIX1 = TRIX(security,check_date, N = 12, M = 20)
    TRIX11=TRIX1[security]
    MATRIX11=MATRIX1[security]
    dev_type = None
    if TRIX1[security]>MATRIX1[security]:
        
       
        dev_type = -1
    
    elif TRIX1[security] < MATRIX1[security]: 
        
        
        dev_type = 1
    else:  
       
        dev_type = 0
    
    return dev_type

def RS(code):
    security=code
    check_date=g.date
    RSI1 = RSI(security,check_date,  N1=6)
    RSI11=RSI1[security]
    dev_type = None
    if 80>RSI11>55 or RSI11<15:
        
       
        dev_type = -1
    
    elif 50>RSI11>20 or RSI11>85: 
       
        
        dev_type = 1
    else:  
     
        dev_type = 0
    
    return dev_type


